import React, { useState } from 'react';
const { ipcRenderer } = window.require('electron');

const KeyUploader = ({ sshConnected, serverInfo }) => {
  const [config, setConfig] = useState({
    disablePasswordAuth: false
  });

  const [status, setStatus] = useState({
    message: '',
    isError: false,
    loading: false
  });

  const handleConfigChange = (e) => {
    const { name, checked } = e.target;
    setConfig(prev => ({
      ...prev,
      [name]: checked
    }));
  };

  const uploadKey = async () => {
    try {
      setStatus({ message: '正在上传公钥并配置服务器...', isError: false, loading: true });
      const result = await ipcRenderer.invoke('upload-key', {
        host: serverInfo.host,
        port: serverInfo.port,
        username: serverInfo.username,
        password: serverInfo.password,
        disablePassword: config.disablePasswordAuth
      });
      setStatus({ message: result.message, isError: !result.success, loading: false });
    } catch (error) {
      setStatus({ message: `上传公钥失败: ${error.message}`, isError: true, loading: false });
    }
  };

  return (
    <div className="key-uploader">
      <h2>上传公钥并配置</h2>
      <div className="form-group checkbox">
        <input
          type="checkbox"
          id="disablePasswordAuth"
          name="disablePasswordAuth"
          checked={config.disablePasswordAuth}
          onChange={handleConfigChange}
          disabled={status.loading}
        />
        <label htmlFor="disablePasswordAuth">禁用密码登录 (仅允许密钥登录)</label>
      </div>
      <div className="button-group">
        <button
          onClick={uploadKey}
          disabled={status.loading || !sshConnected}
          className="primary-button"
        >
          <span role="img" aria-label="upload">⬆️</span> 上传公钥并配置服务器
        </button>
      </div>
      {status.message && (
        <div className={`status-message ${status.isError ? 'error' : ''}`}>
          {status.message}
          {status.loading && <span className="loading-spinner"></span>}
        </div>
      )}
    </div>
  );
};

export default KeyUploader; 